package 接口测试;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import org.json.JSONObject;

public class ApiClient {
    private String url;
    private String authorization;
    private DeviceInfo deviceInfo;

    public ApiClient(String tokenUrl, String appId, String appKey) {
        this.url = tokenUrl;
        this.deviceInfo = new DeviceInfo();
        generate(appId, appKey);
    }

    public void generate(String appId, String appKey) {
        // 假设这里获取设备信息
        this.deviceInfo.brandName = "OPPO"; // 替换为实际品牌名称
        this.deviceInfo.brandType = "A1"; // 替换为实际型号

        String authorization = appId + ":" + appKey;
        this.authorization = Base64.getEncoder().encodeToString(authorization.getBytes());
    }

    public String request() throws Exception {
        String deviceInfoJson = new JSONObject(this.deviceInfo).toString();
        String requestUrl = this.url + "?device_info=" + deviceInfoJson + "&grant_type=api_credentials";

        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization",  this.authorization);

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            return response.toString();
        } else {
            throw new RuntimeException("Failed : HTTP error code : " + responseCode);
        }
    }

    private static class DeviceInfo {
        public String brandName;
        public String brandType;
    }

    public static void main(String[] args) {
        try {
            String tokenUrl = "https://imh.dentalxjtu.com/dhccam/token/generate"; // 替换为实际 URL
            String appId = "'f0b03192-36a6-f3d0-4f48-8f659077f81d"; // 替换为实际 App ID
            String appKey = "'867b9ee3c91916f5f1edae293fb6e7a8'"; // 替换为实际 App Key

            ApiClient client = new ApiClient(tokenUrl, appId, appKey);
            String response = client.request();
            System.out.println("Response: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
